<template lang="pug">
.view.cp-mission-approve.fix-flex-pos
  //- 查询
  el-form.appr-search(:inline="true")
    el-row
      el-form-item
        el-radio-group(v-model="taskType" @change="taskTypeChange")
          el-radio-button(:label="0") 由我提交
          el-radio-button(:label="1") 待我审批
      el-form-item
        el-select.select-width(v-model="timeType", placeholder="请选择")
          el-option(key="0", label="提交时间", :value="0")
          el-option(key="1", label="审批时间", :value="1")
      el-form-item
        el-date-picker.date-width(
          v-model="dateRange",
          type="daterange",
          unlink-panels,
          start-placeholder="开始日期",
          end-placeholder="结束日期",
          value-format="timestamp",
          :default-time="['00:00:00', '23:59:59']")
      el-form-item(label="审批人 :", v-show="taskType == 0")
        el-select.select-width(v-model="endorserID", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in empSelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="提交人 :", v-show="taskType == 1")
        el-select.select-width(v-model="submitterID", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in empSelect",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="审批类型 :")
        el-select.select-width(v-model="endorsementType", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in allApproveType",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item(label="状态 :")
        el-select.select-width(v-model="status", placeholder="请选择")
          el-option(label="全部", :value="null")
          el-option(
            v-for="(item, index) in allApproveStatus",
            :key="index",
            :label="item.name",
            :value="item.value")
      el-form-item
        el-button(type="primary", @click="search") 搜索
      //- el-form-item
          el-button(plain, @click="exportReport") 导出
    //- 表格
  .appr-table
    el-table(
      :data="approveList",
      highlight-current-row,
      v-loading="listLoading",
      size="mini",
      height="100%")
      el-table-column(show-overflow-tooltip, type="index", :index="indexMethod", label="序号")
      el-table-column(show-overflow-tooltip, label="提交时间", min-width="90px")
        template(slot-scope="scope")
          span {{scope.row.submissionTime | date-format}}
      el-table-column(show-overflow-tooltip, prop="submitter", label="提交人")
        template(slot-scope="scope")
          span {{scope.row.submitter | compare-list(empSelect)}}
      el-table-column(show-overflow-tooltip, prop="endorsementType", label="审批类型")
        template(slot-scope="scope")
          span {{scope.row.endorsementType | compare-list(allApproveType)}}
      el-table-column(show-overflow-tooltip, prop="endorsementStatus", label="状态")
        template(slot-scope="scope")
          span {{scope.row.endorsementStatus | multiLine}}
      el-table-column(label="审批时间", min-width="160px")
        template(slot-scope="scope")
          span {{scope.row.endorsementTime | multiLine}}
      el-table-column(show-overflow-tooltip, prop="endorsers", label="审批人")
        template(slot-scope="scope")
          span {{scope.row.endorsers | multiLine}}
      el-table-column(show-overflow-tooltip, prop="remark", label="备注")
      el-table-column(label="操作", min-width="120px")
        template(slot-scope="scope")
          div(v-show="taskType == 0")
            el-tooltip(content="查看")
              i.icon-act.el-icon-view(@click="viewItem(scope.row)")
            el-tooltip(content="编辑", v-if="scope.row.status == 4")
              i.icon-act.el-icon-edit(@click="editItem(scope.row)")
            el-tooltip(content="撤回")
              i.icon-act.el-icon-hy-back(@click="backItem(scope.row, scope.$index)")
            el-tooltip(content="删除")
              i.icon-act.el-icon-delete(@click="deleteItem(scope.row, scope.$index)")
          div(v-show="taskType == 1")
            el-tooltip(content="查看")
              i.icon-act.el-icon-view(@click="viewItem(scope.row)")
            el-tooltip(content="同意", v-if="controlAction(scope.row)")
              i.icon-act.el-icon-check(@click="agreeItem(scope.row, scope.$index)")
            el-tooltip(content="拒绝", v-if="controlAction(scope.row)")
              i.icon-act.el-icon-close(@click="rejectItem(scope.row, scope.$index)")
            el-tooltip(content="撤回", v-if="controlAction(scope.row)")
              i.icon-act.el-icon-hy-back(@click="approveBack(scope.row, scope.$index)")
            el-tooltip(content="打回", v-if="controlAction(scope.row)")
              i.icon-act.el-icon-back(@click="returnApprove(scope.row, scope.$index)")
  //- 分页
  el-pagination.appr-pagination(
    background,
    layout="total, prev, pager, next, jumper",
    prev-text="上一页",
    next-text="下一页",
    @current-change="pageChange",
    :current-page="pageNum",
    :page-size="pageSize",
    :total="totalNum")
  component(
    :is="currentComponent",
    :title="dialogTitle",
    :visible="showDialog",
    :is-edit="isEdit",
    :parent-data="formData",
    :only-submit="true",
    @submit="onFormSubmit",
    @close="showDialog = false")
  OrderView(:visible="showOrderView", :formData="orderData", @close="showOrderView=false")
  OrderEdit(:visible="showOrderEdit", :formData="orderData", @close="showOrderEdit=false", @save="saveOrder")
  PlanView(:visible="showPlanView", :formData="planData", @close="showPlanView=false")
  PlanEdit(:visible="showPlanEdit", :formData="planData", @close="showPlanEdit=false", @save="savePlan")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import ApproveApi from '@/api/mission';
import PurApi from '@/api/purchase';
import InvApi from '@/api/inventory/inbound';
// 采购
import OrderView from '@/components/purchase/order/OrderView';
import OrderEdit from '@/components/purchase/order/OrderEdit';
import PlanView from '@/components/purchase/plan/PlanView';
import PlanEdit from '@/components/purchase/plan/PlanEdit';
// 库存
import outbuyInbound from '../../inventory/inbound/outbuyInbound';
import productInbound from '../../inventory/inbound/productInbound';
import entrustInbound from '../../inventory/inbound/entrustInbound';
import salesreturnInbound from '../../inventory/inbound/salesreturnInbound';
import materialInbound from '../../inventory/inbound/materialInbound';
import otherInbound from '../../inventory/inbound/otherInbound';
import receiveOutbound from '../../inventory/outbound/receiveOutbound';
import feederOutbound from '../../inventory/outbound/feederOutbound';
import outreturnOutbound from '../../inventory/outbound/outreturnOutbound';
import entrustOutbound from '../../inventory/outbound/entrustOutbound';
import salesOutbound from '../../inventory/outbound/salesOutbound';
import otherOutbound from '../../inventory/outbound/otherOutbound';
import checkoutForm from '../../inventory/checkout/checkoutForm';
import allotForm from '../../inventory/allot/allotForm';
import assemblyForm from '../../inventory/assembly/assemblyForm';

export default {
  name: 'misapprove',
  components: {
    OrderView,
    OrderEdit,
    PlanView,
    PlanEdit
  },
  data() {
    return {
      listLoading: false,
      // 搜索条件
      taskType: 0,
      timeType: 0,
      dateRange: [],
      submitterID: null,
      endorserID: null,
      endorsementType: null,
      status: null,
      // 数据
      approveList: [],
      // 分页
      pageSize: 20,
      pageNum: 1,
      totalNum: 0,
      // 库存弹窗
      currentComponent: outbuyInbound,
      dialogTitle: '入库审核',
      showDialog: false,
      // 能编辑  true--能 false--不能
      isEdit: false,
      // 新建时初始数据
      formData: {},
      // 采购计划
      planData: { materiels: [] },
      showPlanView: false,
      showPlanEdit: false,
      // 采购订单
      orderData: {
        materiels: [],
        finances: [],
        terms: [],
        bills: []
      },
      showOrderView: false,
      showOrderEdit: false,
      allApproveType: [],
      allApproveStatus: []
    };
  },
  computed: {
    ...mapGetters(['employeeId', 'empSelect'])
  },
  filters: {
    // 多行
    multiLine(value) {
      let multiStr = null;
      if (value) {
        multiStr = value.replace(/,/g, '\n');
      }
      return multiStr;
    },
  },
  created () {
    // 状态列表
    ComApi.getStatus({ orderType: 'approve' }).then((statusList) => {
      this.allApproveStatus = statusList;
    });
    // 类别列表
    ComApi.getTypes({ orderType: 'approve' }).then((typeList) => {
      this.allApproveType = typeList;
    });
  },
  mounted() {
    this.loadApproveList();
  },
  methods: {
    indexMethod (i) {
      return ((this.pageNum - 1) * this.pageSize) + (i + 1);
    },
    controlAction(row) {
      const { status } = row;
      if (status == '2' || status == '4') {
        // 状态为已同意和已打回时不显示
        return false;
      } else {
        return true;
      }
    },
    taskTypeChange(type) {
      if (type === 0) {
        this.timeType = 0;
      } else if (type === 1) {
        this.timeType = 1;
      }
      this.loadApproveList();
    },
    loadApproveList() {
      this.listLoading = true;
      const params = {
        taskType: this.taskType,
        submitter: this.submitterID,
        endorser: this.endorserID,
        endorsementType: this.endorsementType,
        status: this.status,
        employNo: this.employeeId,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (this.timeType === 0 && this.dateRange && this.dateRange[0]) {
        params.startSubmissionTime = this.dateRange[0];
        params.endSubmissionTime = this.dateRange[1];
      }
      if (this.timeType === 1 && this.dateRange && this.dateRange[0]) {
        params.startEndorsementTime = this.dateRange[0];
        params.endEndorsementTime = this.dateRange[1];
      }
      ApproveApi.getApproveList(params).then((res) => {
        if (!res.status) {
          this.approveList = res.obj.records;
          this.totalNum = res.obj.totalNum;
        } else {
          this.$message.error(res.comment);
        }
        this.listLoading = false;
      }).catch((error) => {
        this.listLoading = false;
        console.log(JSON.stringify(error));
      });
    },
    // 搜索
    search() {
      if (this.pageNum !== 1) {
        this.pageNum = 1;
      }
      this.loadApproveList();
    },
    // 导出
    exportReport() {},
    // 翻页
    pageChange(pageNum) {
      this.pageNum = pageNum;
      this.loadApproveList();
    },
    // 保存提交成功
    onFormSubmit() {
      this.search();
    },
    // 保存采购订单
    saveOrder (formData) {
      PurApi.saveOrder(formData).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          this.showOrderEdit = false;
          this.search();
        } else {
          this.$message.error(result.comment || '保存失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    // 保存采购计划
    savePlan (formData) {
      PurApi.savePlan(formData).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          this.showPlanEdit = false;
          this.search();
        } else {
          this.$message.error(result.comment || '保存失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    // 日期生成Date对象
    filterDate(data = []) {
      if (!data) {
        return [];
      }
      return data.map((item) => {
        if (item.prodDate) {
          const prodDate = new Date(item.prodDate).getTime();
          return { ...item, prodDate };
        }
        return item;
      });
    },
    // 切换组件
    switchComponent(command, op = '查看') {
      switch (command) {
        case '4':
          this.dialogTitle = `${op}盘点单`;
          this.currentComponent = checkoutForm;
          break;
        case '5':
          this.dialogTitle = `${op}调拨单`;
          this.currentComponent = allotForm;
          break;
        case '6':
          this.dialogTitle = `${op}组装拆卸单`;
          this.currentComponent = assemblyForm;
          break;
        default:
          this.dialogTitle = op;
          this.currentComponent = null;
      }
    },
    // 切换入库出库子组件
    switchSubComponent(parent, child, op = '查看') {
      if (parent === '3') {
        // 入库
        switch (child) {
          case '0':
            this.dialogTitle = `${op}外购入库单`;
            this.currentComponent = outbuyInbound;
            break;
          case '1':
            this.dialogTitle = `${op}委外入库单`;
            this.currentComponent = entrustInbound;
            break;
          case '2':
            this.dialogTitle = `${op}生产产品入库单`;
            this.currentComponent = productInbound;
            break;
          case '3':
            this.dialogTitle = `${op}生产退料入库单`;
            this.currentComponent = materialInbound;
            break;
          case '4':
            this.dialogTitle = `${op}销售退货入库单`;
            this.currentComponent = salesreturnInbound;
            break;
          case '5':
            this.dialogTitle = `${op}其他入库单`;
            this.currentComponent = otherInbound;
            break;
          default:
            this.dialogTitle = op;
            this.currentComponent = null;
        }
      } else if (parent === '2') {
        // 出库
        switch (child) {
          case '0':
            this.dialogTitle = `${op}生产领料出库单`;
            this.currentComponent = receiveOutbound;
            break;
          case '1':
            this.dialogTitle = `${op}生产补料出库单`;
            this.currentComponent = feederOutbound;
            break;
          case '2':
            this.dialogTitle = `${op}外购退料出库单`;
            this.currentComponent = outreturnOutbound;
            break;
          case '3':
            this.dialogTitle = `${op}委外出库单`;
            this.currentComponent = entrustOutbound;
            break;
          case '4':
            this.dialogTitle = `${op}销售出库单`;
            this.currentComponent = salesOutbound;
            break;
          case '5':
            this.dialogTitle = `${op}其他出库单`;
            this.currentComponent = otherOutbound;
            break;
          default:
            this.dialogTitle = op;
            this.currentComponent = null;
        }
      }
    },
    // 获取订单详情
    getOrderDetail(currentRow, isEdit) {
      const { endorsementType, contentID } = currentRow;
      if (endorsementType === '0') {
        // 采购计划
        PurApi.getPlanDetail({ id: contentID }).then((result) => {
          if (!result.status) {
            this.planData = result.obj;
            if (isEdit) {
              this.showPlanEdit = true;
            } else {
              this.showPlanView = true;
            }
          } else {
            this.$message.error(result.comment);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      } else if (endorsementType === '1') {
        // 采购订单
        PurApi.getOrderDetail({ id: contentID }).then((result) => {
          if (!result.status) {
            this.orderData = result.obj;
            if (isEdit) {
              this.showOrderEdit = true;
            } else {
              this.showOrderView = true;
            }
          } else {
            this.$message.error(result.comment);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      } else if (endorsementType === '2') {
        // 出库
        InvApi.detailInvOutbound({ orderNo: contentID }).then((res) => {
          this.formData = {
            ...res,
            outboundTime: new Date(res.outboundTime),
            skuArray: this.filterDate(res.skuArray)
          };
          this.showDialog = true;
          this.isEdit = isEdit;
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      } else if (endorsementType === '3') {
        // 入库
        InvApi.detailInvInbound({ orderNo: contentID }).then((res) => {
          this.formData = {
            ...res,
            inboundTime: new Date(res.inboundTime),
            skuArray: this.filterDate(res.skuArray)
          };
          this.showDialog = true;
          this.isEdit = isEdit;
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      } else if (endorsementType === '4') {
        // 盘点
        InvApi.detailInvCheckout({ orderNo: contentID }).then((res) => {
          if (res.status === 0 && res.obj) {
            this.formData = {
              ...res.obj,
              checkoutTime: new Date(res.obj.checkoutTime),
              skuArray: this.filterDate(res.obj.skuArray)
            };
            this.showDialog = true;
            this.isEdit = isEdit;
          } else {
            this.$message.error(res.comment);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      } else if (endorsementType === '5') {
        // 调拨
        InvApi.detailInvAllot({ orderNo: contentID }).then((res) => {
          if (res.status === 0 && res.obj) {
            this.formData = {
              ...res.obj,
              transferTime: new Date(res.obj.transferTime),
              skuArray: this.filterDate(res.obj.skuArray)
            };
            this.showDialog = true;
            this.isEdit = isEdit;
          } else {
            this.$message.error(res.comment);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      } else if (endorsementType === '6') {
        // 组拆
        InvApi.detailInvAssembly({ orderNo: contentID }).then((res) => {
          if (res.status === 0 && res.obj) {
            this.formData = {
              ...res.obj,
              assemdisassemblyTime: new Date(res.obj.assemdisassemblyTime),
              sourceSKUArray: this.filterDate(res.obj.sourceSKUArray),
              targetSKUArray: this.filterDate(res.obj.targetSKUArray)
            };
            this.showDialog = true;
            this.isEdit = isEdit;
          } else {
            this.$message.error(res.comment);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      }
    },
    // 查看
    viewItem(currentRow) {
      const { endorsementType, contentType } = currentRow;
      if (contentType) {
        this.switchSubComponent(endorsementType, contentType, '查看');
      } else {
        this.switchComponent(endorsementType, '查看');
      }
      this.getOrderDetail(currentRow, false);
    },
    // 编辑
    editItem(currentRow) {
      const { endorsementType, contentType } = currentRow;
      if (contentType) {
        this.switchSubComponent(endorsementType, contentType, '编辑');
      } else {
        this.switchComponent(endorsementType, '编辑');
      }
      this.getOrderDetail(currentRow, true);
    },
    // 撤回
    backItem(currentRow) {
      const params = {
        id: currentRow.id,
        endorsementPlanID: currentRow.endorsementPlanID,
        contentType: currentRow.contentType,
        contentID: currentRow.contentID,
        endorsementType: currentRow.endorsementType,
        endorser: this.employeeId
      };
      ApproveApi.verbApprove(params).then((res) => {
        if (!res.status) {
          this.$message({ message: '撤回成功', type: 'success' });
          this.search();
        } else {
          this.$message.error(res.comment || '撤回失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 删除
    deleteItem(currentRow, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: currentRow.id,
          endorsementPlanID: currentRow.endorsementPlanID,
          contentType: currentRow.contentType,
          contentID: currentRow.contentID,
          endorsementType: currentRow.endorsementType,
          endorser: this.employeeId
        };
        ApproveApi.deleteApprove(params).then((res) => {
          if (!res.status) {
            this.approveList.splice(index, 1);
            this.totalNum = this.totalNum - 1;
            this.$message({ message: '删除成功', type: 'success' });
          } else {
            this.$message.error(res.comment || '删除失败');
          }
        });
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    // 同意
    agreeItem(currentRow) {
      this.$prompt('请输入备注', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        const params = {
          id: currentRow.id,
          endorsementPlanID: currentRow.endorsementPlanID,
          contentType: currentRow.contentType,
          contentID: currentRow.contentID,
          endorsementType: currentRow.endorsementType,
          endorser: this.employeeId,
          remark: value
        };
        ApproveApi.agreeApprove(params).then((res) => {
          if (!res.status) {
            this.$message({ message: '审批成功', type: 'success' });
            this.search();
          } else {
            this.$message.error(res.comment || '审批失败');
          }
        });
      }).catch(() => {
        this.$message({ type: 'info', message: '取消输入' });
      });
    },
    // 拒绝
    rejectItem(currentRow) {
      this.$prompt('请输入备注', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        const params = {
          id: currentRow.id,
          endorsementPlanID: currentRow.endorsementPlanID,
          contentType: currentRow.contentType,
          contentID: currentRow.contentID,
          endorsementType: currentRow.endorsementType,
          endorser: this.employeeId,
          remark: value
        };
        ApproveApi.rejectApprove(params).then((res) => {
          if (!res.status) {
            this.$message({ message: '审批成功', type: 'success' });
            this.search();
          } else {
            this.$message.error(res.comment || '失败');
          }
        });
      }).catch(() => {
        this.$message({ type: 'info', message: '取消输入' });
      });
    },
    // 审核撤回
    approveBack(currentRow) {
      const params = {
        id: currentRow.id,
        endorsementPlanID: currentRow.endorsementPlanID,
        contentType: currentRow.contentType,
        contentID: currentRow.contentID,
        endorsementType: currentRow.endorsementType,
        endorser: this.employeeId
      };
      ApproveApi.revokeApprove(params).then((res) => {
        if (!res.status) {
          this.$message({ message: '撤回成功', type: 'success' });
          this.search();
        } else {
          this.$message.error(res.comment || '撤回失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 审核打回
    returnApprove(currentRow) {
      const params = {
        id: currentRow.id,
        endorsementPlanID: currentRow.endorsementPlanID,
        contentType: currentRow.contentType,
        contentID: currentRow.contentID,
        endorsementType: currentRow.endorsementType,
        endorser: this.employeeId
      };
      ApproveApi.returnApprove(params).then((res) => {
        if (!res.status) {
          this.$message({ message: '打回成功', type: 'success' });
          this.search();
        } else {
          this.$message.error(res.comment || '打回失败');
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
  },
  beforeRouteEnter (to, from, next) {
    next();
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 56px
$SELECTWIDTH: 100px
.cp-mission-approve
  .appr-search
    height: $SEARCHHEIGHT
    padding: 12px 0 12px 16px
    overflow-x: auto
    overflow-y: hidden
    white-space: nowrap
    .select-width
      width: $SELECTWIDTH
    .date-width
      width: 260px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      margin-left: 6px
      padding-right: 6px
    .el-date-editor .el-range__close-icon
      width: 20px
    .el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label
      height: 32px
  .appr-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: 56px
    left: 16px
    right: 16px
    overflow-x: hidden
    overflow-y: auto
    &::before
      display: none
    .el-table .cell
      white-space: pre-line
    .icon-act
      font-size: 16px
      font-weight: 500
      cursor: pointer
      margin-left: 3px
      margin-right: 3px
      &:hover
        color: #5D9BFB
  .el-table
    th, td
      text-align: center
  .appr-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
</style>
